
package p.ithorns.framework.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * i18n util
 */
public class I18nUtil {

    private static final Logger log = LoggerFactory.getLogger(I18nUtil.class);

    private static Properties prop = null;

    public static Properties loadI18nProp() {
        if (prop != null) {
            return prop;
        }
        try {
            // build i18n prop
            String i18n = "";
            i18n = StringUtil.isNotBlank(i18n) ? ("_" + i18n) : i18n;
            String i18nFile = MessageFormat.format("i18n/messages{0}.properties", i18n);

            // load prop
            Resource resource = new ClassPathResource(i18nFile);
            EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
            prop = PropertiesLoaderUtils.loadProperties(encodedResource);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return prop;
    }

    /**
     * get val of i18n key
     *
     * @param key key
     * @return value
     */
    public static String getString(String key) {
        Properties properties = loadI18nProp();
        if (null == properties) {
            return "";
        }
        return properties.getProperty(key);
    }

    /**
     * get multi val of i18n multi key, as json
     *
     * @param keys keys
     * @return values
     */
    public static String getMultiString(String... keys) {
        Map<String, String> map = new HashMap<String, String>();

        Properties prop = loadI18nProp();
        if (keys != null && keys.length > 0) {
            for (String key : keys) {
                map.put(key, prop.getProperty(key));
            }
        } else {
            for (String key : prop.stringPropertyNames()) {
                map.put(key, prop.getProperty(key));
            }
        }

        return JsonUtil.toJson(map);
    }

}